package com.chenyun.common.config;

import com.chenyun.common.utils.ThreadUtil;
import lombok.Data;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池相关
 *
 * @author: Lonni
 * @date: 2022/8/8 0008 15:52
 */
@Configuration
@Data
public class ThreadConfig {

    /**
     * 核心线程数 50
     */
    @Value("${chenyun.threadPool.corePoolSize:5}")
    private int corePoolSize;
    /**
     * 最大线程数 200
     */
    @Value("${chenyun.threadPool.maxPoolSize:7}")
    private int maxPoolSize;
    /**
     * 队列最大长度
     */
    @Value("${chenyun.threadPool.queueCapacity:1000}")
    private int queueCapacity ;
    /**
     * 线程池维护线程所允许的空闲时间
     */
    @Value("${chenyun.threadPool.keepAliveSeconds:300}")
    private int keepAliveSeconds = 300;


    /**
     * 线程池
     * @return
     */
    @Bean("threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        //设置前缀
        taskExecutor.setThreadNamePrefix("chenyun-threadpooltask-");
        //拒绝策略
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return taskExecutor;
    }


    /**
     * 定时调度线程池
     * @return
     */
    @Bean("scheduledExecutorService")
    public ScheduledExecutorService scheduledExecutorService(){
        return new ScheduledThreadPoolExecutor(corePoolSize,
                new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(),
                new ThreadPoolExecutor.CallerRunsPolicy())
        {
            @Override
            protected void afterExecute(Runnable r, Throwable t)
            {
                super.afterExecute(r, t);
                ThreadUtil.printException(r,t);
            }
        };
    }

}
